package com.fingard.dsp.bank.directbank.citic01;

import com.alibaba.fastjson.JSON;
import com.fingard.net.FormSubmit;
import sun.misc.BASE64Decoder;

import java.io.File;
import java.math.BigDecimal;
import java.util.*;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.dbobj.receipt.ReceiptMapping;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.bankInterface.IReceipt;
import com.fingard.dsp.bank.helpers.HelperResp;
import com.fingard.dsp.bank.helpers.ReceiptFileSaveHelper;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.ReqQryReceipt;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.RetAtsReceipt;
import com.fingard.io.FileHelper;
import com.fingard.net.ConnState;
import com.fingard.text.StringHelper;
import com.fingard.util.*;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

public class CITIC01Receipt extends CITIC01Base implements IReceipt {
    //交易传入的数据
    private String receiptSaveToMainDir = "";
    private static TransIDHelper _idHelper = new TransIDHelper(1, 9999);

    public RetAtsReceipt qryReceipt(final ReqQryReceipt p_reqReceipt) throws Exception {
        //余额查询返回ATS的对象
        RetAtsReceipt retAts = new RetAtsReceipt(p_reqReceipt.reqHeader);
        download(p_reqReceipt);
        retAts.respCode = "0";
        retAts.respInfo = "后台处理中";
        retAts.writeRetToATS();
        return retAts;
    }

    public void download(ReqQryReceipt p_reqReceipt) {
        //余额查询返回ATS的对象
        String uploadType = SmbFileUtil.getUploadType();
        try {
            boolean receiptUploadShared = this.getBankConfig().getValueAsBool("receiptUploadShared");
            ReceiptFileSaveHelper saveHelper = new ReceiptFileSaveHelper(this);

            String tmpRespCode = "";
            String tmpRespInfo = "";
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_reqReceipt.getDateFrom());

            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_reqReceipt.getDateTo());

            int tmpNowStartRecord = 0;//总条数
            int intPageNumber = 1;//页码数 默认查询第一页
            int tmpNowReadedCount = 0;//已读条数
            boolean tmpQryNext = true;

            String[] tmpStrRet = new String[]{"", ""};

            while (tmpQryNext && tmpRespCode.length() == 0) {
                //赋值通用参数
                CITIC01Header bankHeader = new CITIC01Header();
                bankHeader.action = "DLEDDRSQ";

                XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                //写入通用的头部节点
                writeCommonHeader(xmlWriter, bankHeader);
                String qryType = p_reqReceipt.qryType;
                if (StringHelper.isNullOrEmpty(qryType)) {
                    int cmpRe = DateHelper.compareDay(new Date(), p_reqReceipt.getDateFrom());
                    if (cmpRe == 0) {
                        qryType = "1";
                    } else {
                        qryType = "2";//1：T+0 2：T+1
                    }
                }
                xmlWriter.writeElementString("qryType", qryType);//1：T+0 2：T+1
                xmlWriter.writeElementString("accNo", p_reqReceipt.actNum);
                if (StringHelper.isNullOrEmpty(p_reqReceipt.billType)) {
                    xmlWriter.writeElementString("billType", "0");
                } else {
                    xmlWriter.writeElementString("billType", p_reqReceipt.billType);
                }
                xmlWriter.writeElementString("minAmt", "0.00");
                xmlWriter.writeElementString("maxAmt", "9999999999999.99");
                xmlWriter.writeElementString("startDate", p_reqReceipt.dateFrom);
                xmlWriter.writeElementString("endDate", p_reqReceipt.dateTo);
                xmlWriter.writeElementString("pageSize", getBankConfig().getValueAsString("pageSize"));
                xmlWriter.writeElementString("startNo", String.valueOf(intPageNumber));

                xmlWriter.writeEndDocument();
                tmpStrRet = sendToBank(xmlWriter.toXmlString());
                //模拟返回数据
                /* tmpStrRet = new String[]{"","<?xml version=\"1.0\" encoding=\"GBK\"?><stream><status>AAAAAAA</status><statusText>交易成功</statusText><totalCount>9</totalCount><list name=\"userDataList\"><row><billType>200000</billType><bizTpdes>二代支付</bizTpdes><bizType>200000</bizType><brseqNo>2017032020000020170320J00000045317890000010001</brseqNo><cryType>001</cryType><payeeAccNm>谤循鞘陆华绍织赫扒晰公司</payeeAccNm><payeeAccNo>1204068909000010958</payeeAccNo><payerAccNm>浙姜善将带世衔迷葬锣扒晰公司</payerAccNm><payerAccNo>7331010182300020758</payerAccNo><tranAmt>13069.00</tranAmt><tranCode>3505700</tranCode><tranDate>20170320</tranDate><transeqNo>COBS20170320132851266368000000291423</transeqNo></row><row><billType>200000</billType><bizTpdes>二代支付</bizTpdes><bizType>200000</bizType><brseqNo>2017032020000020170320J00000045318520000010001</brseqNo><cryType>001</cryType><payeeAccNm>社男瘦坪的搓艰一眷阉娱拱泵扒晰公司</payeeAccNm><payeeAccNo>31598503001266194</payeeAccNo><payerAccNm>浙姜善将带世衔迷葬锣扒晰公司</payerAccNm><payerAccNo>7331010182300020758</payerAccNo><tranAmt>21700.00</tranAmt><tranCode>3505700</tranCode><tranDate>20170320</tranDate><transeqNo>COBS20170320133015294495000000291908</transeqNo></row><row><billType>200000</billType><bizTpdes>二代支付</bizTpdes><bizType>200000</bizType><brseqNo>2017032020000020170320J00000045510810000010001</brseqNo><cryType>001</cryType><payeeAccNm>巫姜其姜项肝骂织丢扒晰眺彭公司</payeeAccNm><payeeAccNo>32201997638050622965</payeeAccNo><payerAccNm>浙姜善将带世衔迷葬锣扒晰公司</payerAccNm><payerAccNo>7331010182300020758</payerAccNo><tranAmt>39856.00</tranAmt><tranCode>3505700</tranCode><tranDate>20170320</tranDate><transeqNo>COBS20170320131934691229000000288267</transeqNo></row><row><billType>200000</billType><bizTpdes>二代支付</bizTpdes><bizType>200000</bizType><brseqNo>2017032020000020170320J00000045510830000010001</brseqNo><cryType>001</cryType><payeeAccNm>礁州正窝狞织扒晰公司</payeeAccNm><payeeAccNo>201000098123344</payeeAccNo><payerAccNm>浙姜善将带世衔迷葬锣扒晰公司</payerAccNm><payerAccNo>7331010182300020758</payerAccNo><tranAmt>20248.68</tranAmt><tranCode>3505700</tranCode><tranDate>20170320</tranDate><transeqNo>COBS20170320131710278633000000287535</transeqNo></row><row><billType>200000</billType><bizTpdes>二代支付</bizTpdes><bizType>200000</bizType><brseqNo>2017032020000020170320J00000045510850000010001</brseqNo><cryType>001</cryType><payeeAccNm>情锰贾热织丢扒晰公司</payeeAccNm><payeeAccNo>201000002355529</payeeAccNo><payerAccNm>浙姜善将带世衔迷葬锣扒晰公司</payerAccNm><payerAccNo>7331010182300020758</payerAccNo><tranAmt>4432.00</tranAmt><tranCode>3505700</tranCode><tranDate>20170320</tranDate><transeqNo>COBS20170320131810812189000000287821</transeqNo></row><row><billType>200000</billType><bizTpdes>二代支付</bizTpdes><bizType>200000</bizType><brseqNo>2017032020000020170320J00000045510960000010001</brseqNo><cryType>001</cryType><payeeAccNm>礁州将衡囊狞骂扒晰公司</payeeAccNm><payeeAccNo>19115701040003209</payeeAccNo><payerAccNm>浙姜善将带世衔迷葬锣扒晰公司</payerAccNm><payerAccNo>7331010182300020758</payerAccNo><tranAmt>4525.00</tranAmt><tranCode>3505700</tranCode><tranDate>20170320</tranDate><transeqNo>COBS20170320131547026003000000287131</transeqNo></row><row><billType>200000</billType><bizTpdes>二代支付</bizTpdes><bizType>200000</bizType><brseqNo>2017032020000020170320J00000045513200000010001</brseqNo><cryType>001</cryType><payeeAccNm>敢忙挑中狞克狞骂扒晰公司</payeeAccNm><payeeAccNo>1205280219000000209</payeeAccNo><payerAccNm>浙姜善将带世衔迷葬锣扒晰公司</payerAccNm><payerAccNo>7331010182300020758</payerAccNo><tranAmt>57601.00</tranAmt><tranCode>3505700</tranCode><tranDate>20170320</tranDate><transeqNo>COBS20170320132342275672000000289606</transeqNo></row><row><billType>200000</billType><bizTpdes>二代支付</bizTpdes><bizType>200000</bizType><brseqNo>2017032020000020170320J00000045513600000010001</brseqNo><cryType>001</cryType><payeeAccNm>谭州吴捂掳绍织赫扒晰公司</payeeAccNm><payeeAccNo>545001040012718</payeeAccNo><payerAccNm>浙姜善将带世衔迷葬锣扒晰公司</payerAccNm><payerAccNo>7331010182300020758</payerAccNo><tranAmt>9142.75</tranAmt><tranCode>3505700</tranCode><tranDate>20170320</tranDate><transeqNo>COBS20170320132620418203000000290492</transeqNo></row><row><billType>200000</billType><bizTpdes>二代支付</bizTpdes><bizType>200000</bizType><brseqNo>2017032020000020170320J00000045515340000010001</brseqNo><cryType>001</cryType><payeeAccNm>情锰鞘云阜绍织扒晰公司</payeeAccNm><payeeAccNo>372301040003826</payeeAccNo><payerAccNm>浙姜善将带世衔迷葬锣扒晰公司</payerAccNm><payerAccNo>7331010182300020758</payerAccNo><tranAmt>20792.80</tranAmt><tranCode>3505700</tranCode><tranDate>20170320</tranDate><transeqNo>COBS20170320132736776911000000290886</transeqNo></row></list></stream>"};*/
                /*tmpStrRet = new String[]{"", "<?xml version=\"1.0\" encoding=\"GBK\"?><stream><status>AAAAAAA</status><statusText>交易成功</statusText><totalCount>2</totalCount><list name=\"userDataList\"><row><billType>200000</billType><bizTpdes>二代支付</bizTpdes><bizType>200000</bizType><brseqNo>2017032020000020170320J00000045317890000010001</brseqNo><cryType>001</cryType><payeeAccNm>谤循鞘陆华绍织赫扒晰公司</payeeAccNm><payeeAccNo>1204068909000010958</payeeAccNo><payerAccNm>浙姜善将带世衔迷葬锣扒晰公司</payerAccNm><payerAccNo>7331010182300020758</payerAccNo><tranAmt>13069.00</tranAmt><tranCode>3505700</tranCode><tranDate>20170320</tranDate><transeqNo>COBS20170320132851266368000000291423</transeqNo></row><row><billType>200000</billType><bizTpdes>二代支付</bizTpdes><bizType>200000</bizType><brseqNo>2017032020000020170320J00000045510830000010001</brseqNo><cryType>001</cryType><payeeAccNm>礁州正窝狞织扒晰公司</payeeAccNm><payeeAccNo>201000098123344</payeeAccNo><payerAccNm>浙姜善将带世衔迷葬锣扒晰公司</payerAccNm><payerAccNo>7331010182300020758</payerAccNo><tranAmt>20248.68</tranAmt><tranCode>3505700</tranCode><tranDate>20170319</tranDate><transeqNo>COBS20170320131710278633000000287535</transeqNo></row></list></stream>"};*/
                //测试用
                //String testFile = "D:\\getToWork\\14-filesForDevelop\\CITIC01\\回单step1.txt";
                //if(FileHelper.existFile(testFile)){
                //	tmpStrRet[0]="";
                //	tmpStrRet[1]=FileHelper.readFileText(testFile, "gbk");
                //}
                //测试用
                if (tmpStrRet[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String tmpStatus = tmpBkReader.getFirstText("/stream/status");
                        String tmpStatusText = tmpBkReader.getFirstText("/stream/statusText");
                        int totalCount = 0;
                        if (!StringHelper.isNullOrEmpty(tmpBkReader.getFirstText("/stream/totalCount"))) {
                            totalCount = Integer.parseInt(tmpBkReader.getFirstText("/stream/totalCount"));
                        }
                        if (totalCount > 0) {

                            int index = 0;

                            //
                            String tmpDir = "";
                            String temppath = "";
                            String path = "";
                            String tmpDownZipFile = "";
                            Map<String, String> map = new HashMap<String, String>();//存储存放的路径
                            //赋值通用参数
                            CITIC01Header downbankHeader = new CITIC01Header();
                            downbankHeader.action = "DLEDCDTD";
                            XmlTextWriter downxmlWriter = new XmlTextWriter();//发银行报文的XML对象

                            //写入通用的头部节点
                            writeCommonHeader(downxmlWriter, downbankHeader);

                            downxmlWriter.writeElementString("bankId", "302");
                            downxmlWriter.writeElementString("isCurrDay", qryType);//是否为T+0 日varchar (1)， 1：是；2：否
                            downxmlWriter.writeElementString("accNo", p_reqReceipt.actNum);
                            downxmlWriter.writeStartElementByAttr("list", "<list name=\"userDataList\">");
                            StringBuilder json = new StringBuilder();
                            if(getBankConfig().getValueAsBool("receiptPushHasTenantId")){
                                json.append("tenantId="+FGBiz.dspCenter.dspSet.tenant+"&transType=downloadreceipt&data={\"rows\":[");
                            }else{
                                json.append("transType=downloadreceipt&data={\"rows\":[");
                            }
                            Map<String, String> contentMap = new HashMap<String, String>();
                            Map<String, ReceiptMapping> mapForRcptObj = new HashMap<String, ReceiptMapping>();
                            while (tmpBkReader.read("/stream/list/row")) {
                                index++;
                                if (tmpStatus != null && tmpStatus.equals("AAAAAAA")) {
                                    String billType = tmpBkReader.readedXElement.getSingleText("billType");
                                    String brseqNo = tmpBkReader.readedXElement.getSingleText("brseqNo");

                                    String brseqNoAts = "";
                                    boolean flag = false;
                                    if (StringHelper.hasAnyChar(brseqNo) && brseqNo.trim().length() > 9) {
                                        //回单时间
                                        int receiptDate = Integer.parseInt(brseqNo.trim().substring(0, 8));
                                        if (StringHelper.hasAnyChar(getBankConfig().getValueAsString("brseqNoAvailDate"))) {
                                            //生效时间
                                            int availDate = Integer.parseInt(getBankConfig().getValueAsString("brseqNoAvailDate"));
                                            if (receiptDate >= availDate) {
                                                if (brseqNo.trim().length() == 28) {
                                                    brseqNoAts = brseqNo.trim().substring(8);
                                                    flag = true;
                                                } else if (brseqNo.trim().length() > 28) {
                                                    brseqNoAts = brseqNo.trim().substring(brseqNo.trim().length() - 24, brseqNo.trim().length() - 4);
                                                    flag = true;
                                                }
                                            }
                                        }
                                    }
                                    String recAct = "";
                                    String recName = "";
                                    String cryType = "";
                                    if ("1".equals(qryType)) {
                                        recAct = tmpBkReader.readedXElement.getSingleText("otherRaccNo1");
                                        recName = tmpBkReader.readedXElement.getSingleText("otherRaccNm1");
                                        cryType = tmpBkReader.readedXElement.getSingleText("cryType1");
                                        if (p_reqReceipt.actNum.equals(recAct)) {
                                            recAct = tmpBkReader.readedXElement.getSingleText("accNo1");
                                            recName = tmpBkReader.readedXElement.getSingleText("accNm1");
                                        } else {
                                            recAct = tmpBkReader.readedXElement.getSingleText("otherRaccNo1");
                                            recName = tmpBkReader.readedXElement.getSingleText("otherRaccNm1");
                                        }
                                    } else {
                                        recAct = tmpBkReader.readedXElement.getSingleText("payeeAccNo");
                                        recName = tmpBkReader.readedXElement.getSingleText("payeeAccNm");
                                        cryType = tmpBkReader.readedXElement.getSingleText("cryType");
                                        if (p_reqReceipt.actNum.equals(recAct)) {
                                            recAct = tmpBkReader.readedXElement.getSingleText("payerAccNo");
                                            recName = tmpBkReader.readedXElement.getSingleText("payerAccNm");
                                        } else {
                                            recAct = tmpBkReader.readedXElement.getSingleText("payeeAccNo");
                                            recName = tmpBkReader.readedXElement.getSingleText("payeeAccNm");
                                        }
                                    }
                                    String tranAmt = tmpBkReader.readedXElement.getSingleText("tranAmt");
                                    String brStt = tmpBkReader.readedXElement.getSingleText("brStt");
                                    String cdFlag = tmpBkReader.readedXElement.getSingleText("cdfg");
                                    if (!StringHelper.isNullOrEmpty(cdFlag)) {
                                        cdFlag = cdFlag.equals("C") ? "2" : "1";//C：贷/收；D：借/付-->
                                    }
                                    String tranDate = tmpBkReader.readedXElement.getSingleText("tranDate");
                                    String transeqNo = tmpBkReader.readedXElement.getSingleText("transeqNo");

                                    if (!StringHelper.isNullOrEmpty(billType) && !StringHelper.isNullOrEmpty(brseqNo)) {

                                        downxmlWriter.writeStartElement("row");
                                        downxmlWriter.writeElementString("brSeqNo", brseqNo);
                                        //<!--回单类型varchar (6)，100000：存款回单；100001：取款回单；200000：转账回单；200001：缴税回单；300000：收费回单；400000定期回单；400001：活期回单-->
                                        downxmlWriter.writeElementString("billType", billType);
                                        downxmlWriter.writeEndElement();
                                    }
                                    tmpDir = this.getTempFileDirectory() + File.separator + p_reqReceipt.actNum + File.separator + tranDate;
                                    /*FileHelper.mkdir(tmpDir);*/
                                    tmpDownZipFile = tmpDir + File.separator + brseqNo + ".pdf";
                                    map.put(brseqNo + ".pdf", tmpDownZipFile);
                                    WriteBankLogLn("插入map内容为：" + "key:" + brseqNo + "value:" + tmpDownZipFile);
                                    if (tmpDownZipFile.indexOf("tempfile") != -1) {
                                        temppath = new File(tmpDownZipFile).getParent().substring(tmpDownZipFile.indexOf("tempfile") + 9);
                                        path = temppath.replace("\\", "/") + "/";
                                    }

                                    if (receiptUploadShared) {
                                        //记录要推送给ATS的数据 key:回单编号；value:推送的值字符串
                                        StringBuilder sb = new StringBuilder();
                                        sb.append(p_reqReceipt.actNum).append("|").append(p_reqReceipt.actCur).append("|").append(flag ? brseqNoAts : brseqNo).append("|")
                                                .append(brStt).append("|").append(recName).append("|").append(recAct).append("|").append(tranAmt).append("|").append(cdFlag).append("|")
                                                .append(flag ? brseqNoAts : StringHelper.hasAnyChar(transeqNo) ? transeqNo.substring(transeqNo.length() - 14) : transeqNo).append("|").append(tranDate.substring(0, 4) + "-" + tranDate.substring(4, 6) + "-" + tranDate.substring(6)).append("|")
                                                .append(path + new File(tmpDownZipFile).getName()).append("|");
                                        contentMap.put(brseqNo, sb.toString().replaceAll(" ", ""));
                                    } else {
                                        ReceiptMapping eachRcptMp = new ReceiptMapping();
                                        String receiptNo = brseqNo;
                                        //电子回单命名规则（历史回单8+6+22+10）
                                        //8位日期+6位回单类型+8位当日日期+14位回单编号+10序列号
                                        if (receiptNo.length() == 46) {
                                            String other1 = receiptNo.substring(22, 36);
                                            eachRcptMp.addOtherBusRef(other1, other1);
                                        }
                                        eachRcptMp.busRef = transeqNo;
                                        eachRcptMp.bank = "302";
                                        eachRcptMp.setBusDate(Format.Date8Format.parse(tranDate));
                                        eachRcptMp.ownAct = p_reqReceipt.actNum;
                                        eachRcptMp.askNumber = transeqNo;
                                        eachRcptMp.keyName = "receiptNo";
                                        eachRcptMp.receiptNo = receiptNo;
                                        eachRcptMp.amount = new BigDecimal(tranAmt);
                                        mapForRcptObj.put(brseqNo, eachRcptMp);
                                    }

                                } else {
                                    tmpQryNext = false;
                                    WriteBankLogLn(tmpStatusText);
                                }
                            }
                            //while 结束
                            //分多次下载
                            downxmlWriter.writeEndDocument();
                            String[] downTmpStrRet = sendToBank(downxmlWriter.toXmlString());
                            //模拟返回下载的回单数据
            /*downTmpStrRet = new String[]{"", "<?xml version=\"1.0\" encoding=\"GBK\"?>\n" +
                    "<stream><fileConTent>UEsDBBQACAgIABKVUEwAAAAAAAAAAAAAAAAyAAAAMjAxNzAzMjAyMDAwMDAyMDE3MDMyMEowMDAwMDA0NTMxNzg5MDAwMDAxMDAwMS5wZGYDAFBLBwgAAAAAAgAAAAAAAABQSwECFAAUAAgICAASlVBMAAAAAAIAAAAAAAAAMgAAAAAAAAAAAAAAAAAAAAAAMjAxNzAzMjAyMDAwMDAyMDE3MDMyMEowMDAwMDA0NTMxNzg5MDAwMDAxMDAwMS5wZGZQSwUGAAAAAAEAAQBgAAAAYgAAAAAA</fileConTent><fileName>FURCP_TWY_pdf_2018021611518777636712.zip</fileName><size>1</size><status>AAAAAAA</status><statusText>交易成功</statusText><list name=\"userDataList\"><row><billType>200000</billType><brseqNo>2017032020000020170320J00000045317890000010001</brseqNo><pdfName>2017032020000020170320J00000045317890000010001.pdf</pdfName></row></list></stream>"};*/
                            //测试用
                            //String testFile2 = "D:\\getToWork\\14-filesForDevelop\\CITIC01\\回单step2.txt";
                            //if(FileHelper.existFile(testFile2)){
                            //	downTmpStrRet[0]="";
                            //	downTmpStrRet[1]=FileHelper.readFileText(testFile2, "gbk");
                            //}
                            //测试用
                            if (downTmpStrRet[0].length() == 0) {
                                ArrayList<String> listToDelete = new ArrayList<String>();
                                StringBuilder tmpSbMsg1 = new StringBuilder();
                                XmlTextReader downtmpBkReader = loadBankRespXmlReader(downTmpStrRet[1], tmpSbMsg1);
                                if (downtmpBkReader != null) {
                                    String tmpStatus1 = downtmpBkReader.getFirstText("/stream/status");
                                    String tmpStatusText1 = downtmpBkReader.getFirstText("/stream/statusText");
                                    if (tmpStatus1 != null && tmpStatus1.equals("AAAAAAA")) {
                                        String filecontent = downtmpBkReader.getFirstText("/stream/fileConTent");//文件内容
                                        String fileName = downtmpBkReader.getFirstText("/stream/fileName");//名称
                                        String size = downtmpBkReader.getFirstText("/stream/size");//数组
                                        String tmpdir1 = this.getTempFileDirectory() + File.separator + p_reqReceipt.actNum;
                                        FileHelper.mkdir(tmpdir1);
                                        byte[] bytesFileContent = new BASE64Decoder().decodeBuffer(filecontent);
                                        FileHelper.writeBytesToFile(tmpdir1 + File.separator + fileName, bytesFileContent);
                                        listToDelete.add(tmpdir1 + File.separator + fileName);
                                        WriteBankLogLn("开始解压文件" + fileName + "至临时文件夹" + tmpdir1);
                                        ZipHelper.base64Unzip(filecontent, tmpdir1);
                                        while (downtmpBkReader.read("/stream/list/row")) {
                                            //回单编号
                                            String billNo = downtmpBkReader.readedXElement.getSingleText("brseqNo");
                                            //回单PDF文件名
                                            String pdfname = downtmpBkReader.readedXElement.getSingleText("pdfName");
                                            //本地备份文件
                                            for (Map.Entry<String, String> entry : map.entrySet()) {
                                                WriteBankLogLn("获取到的临时文件路径为:" + "key:" + entry.getKey() + "," + "value:" + entry.getValue());
                                            }

                                            tmpDownZipFile = map.get(pdfname);
                                            WriteBankLogLn("获取到的临时文件路径为:" + tmpDownZipFile);
                                            //兼容税类回单（默认返回文件名前面加1）
                                            if (tmpDownZipFile == null) {
                                                tmpDownZipFile = tmpDir + File.separator + pdfname;
                                            }
                                            if (tmpDownZipFile.indexOf("tempfile") != -1) {
                                                temppath = new File(tmpDownZipFile).getParent().substring(tmpDownZipFile.indexOf("tempfile") + 9);
                                                path = temppath.replace("\\", "/") + "/";
                                            }
                                            String temporary = tmpdir1 + File.separator + pdfname;

                                            if (receiptUploadShared) {
                                                String tmpSavePath = receiptSaveToMainDir + File.separator + temppath;
                                                FileHelper.mkdir(tmpSavePath);
                                                String tmpSaveToDir = tmpSavePath + File.separator + pdfname;
                                                if (new File(temporary).exists()) {
                                                    FileHelper.copyFile(new File(temporary), new File(tmpSaveToDir));
                                                    WriteBankLogLn("复制文件" + temporary + "至" + tmpSaveToDir);
                                                }
                                                //上传文件到共享目录下
                                                int result = -1;
                                                String AtsFilePath = "";
                                                String ftpFilePath = "";
                                                String tmpByDate = Format.Date8Format.format(new Date());
                                                tmpByDate = tmpByDate.substring(0, 6) + "/" + tmpByDate.substring(6, 8) + "/" + reqHeader.bankCode + "/" + p_reqReceipt.actNum + "/";
                                                if (!"false".equals(FGBiz.dspCenter.dspSet.receiptShareDir)) {
                                                    if (new File(tmpSaveToDir).exists()) {
                                                        if ("smb".equals(uploadType)) {
                                                            WriteBankLogLn("正在上传文件至共享目录:" + FGBiz.dspCenter.dspSet.receiptShareDir);
                                                            result = SmbFileUtil.smbUploading(tmpSaveToDir, tmpByDate, FGBiz.dspCenter.dspSet.receiptShareDir);
                                                            AtsFilePath = tmpByDate + pdfname;
                                                        } else if ("localhost".equals(uploadType)) {
                                                            String shareDir = StringHelper.trimEndFileSp(FGBiz.dspCenter.dspSet.receiptShareDir.split("@")[1]) + File.separator;
                                                            WriteBankLogLn("正在上传文件至本地共享目录:" + shareDir);
                                                            result = FileHelper.copyFile(tmpSaveToDir, shareDir + tmpByDate + pdfname);
                                                            AtsFilePath = tmpByDate + pdfname;
                                                        } else {
                                                            tmpByDate = tmpByDate.replaceAll(reqHeader.bankCode + "/", "");
                                                            WriteBankLogLn("正在上传文件至微服务:" + FGBiz.dspCenter.dspSet.receiptShareDir);
                                                            Map<String, String> mapResult = FormSubmit.fileUpload
                                                                    (FGBiz.dspCenter.dspSet.receiptShareDir, p_reqReceipt.actNum, tmpSaveToDir, tmpByDate, pdfname, getCharset());
                                                            WriteBankLogStep3(JSON.toJSONString(mapResult));
                                                            if (mapResult.keySet().size() != 0) {
                                                                result = Integer.valueOf(mapResult.get("respCode"));
                                                                tmpByDate = mapResult.get("remotePath");
                                                                AtsFilePath = tmpByDate;
                                                            } else {
                                                                result = -1;
                                                            }
                                                        }

                                                    }
                                                } else {
                                                    //ftp服务
                                                    FtpSet ftpSet2 = FGBiz.dspCenter.dspConfig.getReceiptFtpSet("atsReceipt");
                                                    WriteBankLogLn("正在上传文件至ftp目录:" + ftpSet2.upDir);
                                                    //上传ftp服务器的地址
                                                    AtsFilePath = tmpByDate + pdfname;
                                                    ftpFilePath = StringHelper.trimEndFileSp(ftpSet2.upDir) + "/" + AtsFilePath;
                                                    WriteBankLogLn("开始将回单" + tmpSaveToDir + "上传至" + ftpFilePath);
                                                    //上传至ftp
                                                    result = FtpUtil.ftpUploading(ftpSet2, tmpSaveToDir, ftpFilePath);
                                                }
                                                if (result == 0 || result == 1) {
                                                    if (result == 0) {
                                                        WriteBankLogLn("文件上传成功");
                                                    } else {
                                                        WriteBankLogLn("文件已存在共享目录无需重复上传");
                                                    }

                                                    //推送数据给ATS处理
                                                    if (StringHelper.hasAnyChar(billNo)) {
                                                        if (contentMap.containsKey(billNo)) {
                                                            String[] billArray = contentMap.get(billNo).split("\\|");
                                                            if (billArray.length == 11) {
                                                                String receiptCode = billArray[2];//回单号
                                                                String tranSeqNo = billArray[8];//唯一号
                                                                //ATSES-12699 中信银行回单重复：只加000001，没办法防重
                                                                if (StringHelper.hasAnyChar(receiptCode)) {
                                                                    if ("000001".equals(receiptCode.substring(receiptCode.length() - 6))) {
                                                                        if (StringHelper.hasAnyChar(getBankConfig().getValueAsString("blnAndridAvaiDate"))) {
                                                                            //回单时间
                                                                            int receiptDate = Integer.parseInt(billArray[9].length() == 10 ? DateHelper.convertD10toD8(billArray[9]) : billArray[9]);
                                                                            //生效时间
                                                                            int availDate = Integer.parseInt(getBankConfig().getValueAsString("blnAndridAvaiDate"));
                                                                            if (receiptDate >= availDate) {
                                                                                receiptCode = receiptCode.substring(0, receiptCode.length() - 6) + String.valueOf(receiptDate).substring(2);
                                                                                tranSeqNo = tranSeqNo.substring(0, tranSeqNo.length() - 6) + String.valueOf(receiptDate).substring(2);
                                                                            }
                                                                        }
                                                                    }
                                                                }
                                                                json.append("{");
                                                                json.append("\"actNum\":\"" + billArray[0] + "\",");
                                                                json.append("\"actCur\":\"" + billArray[1] + "\",");
                                                                json.append("\"receiptCode\":\"" + receiptCode + "\",");
                                                                json.append("\"receiptType\":\"" + "" + "\",");
                                                                json.append("\"receiptState\":\"" + billArray[3] + "\",");
                                                                json.append("\"oppActName\":\"" + billArray[4] + "\",");
                                                                json.append("\"oppActNum\":\"" + billArray[5] + "\",");
                                                                json.append("\"amount\":\"" + billArray[6] + "\",");
                                                                json.append("\"moneyway\":\"" + billArray[7] + "\",");
                                                                json.append("\"tranSeqNo\":\"" + tranSeqNo + "\",");
                                                                json.append("\"tranCode\":\"" + "" + "\",");//交易码?
                                                                json.append("\"tranDate\":\"" + billArray[9] + "\",");
                                                                json.append("\"filePath\":\"" + AtsFilePath + "\",");//回单文件仓库存储路径
                                                                json.append("\"fileType\":\"1\"");
                                                                json.append("},");
                                                            }
                                                        }
                                                    }

                                                    if (FileHelper.deleteFileIfExists(temporary)) {
                                                        WriteBankLogLn("已删除临时文件：" + temporary);
                                                    }
                                                } else {
                                                    WriteBankLogLn("上传文件至共享目录失败，请检查共享目录配置是否正确");
                                                }
                                            } else {
                                                if (mapForRcptObj.containsKey(billNo)) {
                                                    ReceiptMapping eachRcptMp = mapForRcptObj.get(billNo);
                                                    eachRcptMp.srcFile = StringHelper.getFileName(temporary);
                                                    HelperResp saveResp = saveHelper.saveByRcptMap(reqHeader, eachRcptMp, temporary);
                                                    WriteBankLogLn(saveResp.sbMsg);
                                                    if (saveResp.isCompleted) {
                                                        //tmpFileCount++;
                                                        listToDelete.add(temporary);
                                                    } else if (ConnState.FAIL.equals(saveResp.connState)) {
                                                        WriteBankLogLn("连接服务器失败，终止本次推送");
                                                        tmpRespCode = "-1";
                                                        tmpRespInfo = "连接服务器失败，终止本次推送";
                                                        //isAllRight = false;
                                                        break;
                                                    } else if (ConnState.CLASS_NOT_FOUND.equals(saveResp.connState)) {
                                                        WriteBankLogLn(ConnState.CLASS_NOT_FOUND + "初始化类异常，终止本次推送");
                                                        tmpRespCode = "-1";
                                                        tmpRespInfo = ConnState.CLASS_NOT_FOUND + "初始化类异常，终止本次推送";
                                                        //isAllRight = false;
                                                        break;
                                                    }
                                                }

                                            }


                                        }
                                    } else {
                                        WriteBankLogLn(tmpStatusText1);
                                    }
                                } else {
                                    WriteBankLogLn(tmpSbMsg1.toString());
                                }
                                if (receiptUploadShared) {
                                    //推送到ATS
                                    json.deleteCharAt(json.length() - 1);
                                    json.append("]}");
                                    String[] data;
                                    String receiptPushType = FGBiz.dspCenter.dspSet.receiptPushType;
                                    if ("nbGateway".equals(receiptPushType)) {
                                        WriteBankLogLn("3.推送给网关的数据" + json.toString());
                                        data = FormSubmit.receiptInfoSend(json.toString(), this);
                                        if (data[0].length() == 0 && data[1].equals("ok")) {
                                            WriteBankLogLn("推送数据到网关成功,请查看数据");
                                        } else {
                                            WriteBankLogLn("推送数据到网关失败");
                                        }
                                    } else {
                                        WriteBankLogLn("3.推送给ATS的数据" + json.toString());
                                        data = sendToATS(json.toString());
                                        if (data[0].length() == 0 && data[1].equals("ok")) {
                                            WriteBankLogLn("推送数据到ATS成功,请查看数据");
                                        } else {
                                            WriteBankLogLn("推送数据到ATS失败");
                                        }
                                    }

                                }

                                int delCount = 0;
                                for (String delFile : listToDelete) {
                                    try {
                                        if (FileHelper.deleteFileIfExists(delFile)) {
                                            delCount++;
                                        }
                                    } catch (Exception ex) {
                                        WriteBankLogLn(ex);
                                    }
                                }
                                WriteBankLogLn("成功删除了" + delCount + "个文件");

                            } else {
                                WriteBankLogLn(downTmpStrRet[1]);
                            }
                            //
                            tmpNowReadedCount += index;
                            if (tmpNowReadedCount < totalCount)//查询下一页
                            {
                                WriteBankLogLn("已查询条数" + tmpNowReadedCount);
                                intPageNumber = intPageNumber + Integer.parseInt(getBankConfig().getValueAsString("pageSize"));//页码加一 查询第二页
                            } else if (tmpNowReadedCount == totalCount)//本次分页查询完毕
                            {
                                tmpQryNext = false;
                                tmpNowReadedCount = 0;
                                continue;
                            }

                        } else {
                            tmpQryNext = false;
                            WriteBankLogLn("账户(" + p_reqReceipt.actNum + ")在" + p_reqReceipt.dateFrom + "到" + p_reqReceipt.dateTo + "没有产生回单数据");
                        }
                    } else {
                        tmpQryNext = false;
                        WriteBankLogLn(tmpSbMsg.toString());
                    }
                } else {
                    tmpQryNext = false;
                    WriteBankLogLn(tmpStrRet[1]);
                }
            }
            /*LogHelper.writeBankLog(_idHelper.getNextID(), new Date(), new Date(), p_reqReceipt.actNum, p_reqReceipt.reqHeader, sbLog);*/
        } catch (Exception e) {
            WriteBankLogLn(e.getMessage());
            e.printStackTrace();
        }
    }
}
